class SocketManager extends SocketNetwork {

    private static _i: SocketManager;
    static get i(): SocketManager {
        return this._i || (this._i = new SocketManager());
    }

    private status: ConnectStatus;
    private timestamp: number;
    private timeoutid: number;

    constructor() {
        super();
    }

    connectToServer() {
        GameConfig.ipConfig();

        this.status = ConnectStatus.connecting;

        let addr: string;
        let port: number;

        if (game.ip && game.port) {
            addr = game.ip;
            port = game.port;
        }
        else if (game.user) {
            addr = GameConfig.servertest_addr;
            port = GameConfig.servertest_port;
        }
        else {
            addr = GameConfig.server_addr;
            port = GameConfig.server_port;
        }

        addr = addr.indexOf('http') != -1 ? addr.split('//')[1] : addr;

        this.timestamp = Date.now();

        this.timeoutid = egret.setTimeout(this.close, this, 10000);

        this.connect(addr, port, addr.indexOf('192') == -1 ? 1 : 2);
    }

    send(cmd: number, data: any = null) {
        data = data ? data : {};

        let obj: any = {};
        obj.sequence = cmd;

        if (data.hasOwnProperty('args')) {
            obj = data;
        }
        else {
            obj.args = data;
        }

        console.log("---------<<Send>>:", JSON.stringify(obj));

        super.send(JSON.stringify(obj));
    }

    readUTF() {
        super.readUTF();

        console.log(">>Read<<=========:", this.data);

        egret.clearTimeout(this.timeoutid);

        switch (this.data) {
            case "start":
            case "\"start\"":
                this.status = ConnectStatus.connected;
                let send: any = {};
                send.args = {};
                send.gameid = GameConfig.gameType;
                send.refer = location.href;

                if (game.user) {
                    send.channel = 'test';
                    send.openid = game.user;
                    send.openkey = '123456788';
                    send.nick = game.user;
                    send.pic = game.player.pic;
                    send.sex = '0';
                }
                else if (!GameStorage.getData(GameStorage.wx_code)) {
                    if (!GameConfig.wx_code) {
                        GameConfig.wxAccess();
                        return;
                    }
                    else {
                        send.code = GameConfig.wx_code;
                        send.length = GameConfig.wx_code.length;
                        send.channel = acelab.platformType();
                    }
                }
                else {
                    send.uid = GameStorage.getData(GameStorage.uid);
                    send.code = GameStorage.getData(GameStorage.code);
                    send.length = GameStorage.getData(GameStorage.code).length;
                }

                this.send(1, send);
                break;
            case "end":
            case "\"end\"":
                this.status = ConnectStatus.connectFail;
                this.close();
                this.loginFail();
                break;
            default:
                this.status = ConnectStatus.connectOld;

                let read: any = JSON.parse(this.data);

                if (!read) {
                    EffectTextUtils.showTips("抱歉!!!", 5);
                    return;
                }

                if (read.code > 0) {
                    gameManager.msgManager.readCode(read.sequence, read.code, read);
                    return;
                }

                gameManager.msgManager.read(read.sequence, read.data);
                break;
        }
    }

    closeHandler() {
        super.closeHandler();

        console.log(Date.now(), this.timestamp, this.timeoutid);

        egret.clearTimeout(this.timeoutid);

        switch (this.status) {
            case ConnectStatus.connecting://连接中断开
                if (Date.now() - this.timestamp < 1000) {
                    this.networkIsNot();
                }
                else {
                    this.connectTimeOut();
                }
                break;
            case ConnectStatus.connected://连接成功后断开
                this.loginConflict();
                break;
            case ConnectStatus.connectFail://连接失败后断开
                this.loginFail();
                break;
            case ConnectStatus.connectOld://游戏过程中断开
            default:
                this.networkNotgood();
                break;
        }
    }

    /**
     * 登录失败
     */
    private loginFail() {
        game.askPanel.showMsg(function (r: boolean) {
            if (r) {
                Weixin.getAccessCode(GameConfig.appid, Weixin.shareUrl(1));
            }
            else {
                Weixin.closeWindow();
            }
        }, "登录失败，是否重新登录？\n取消将退出游戏。", "重新登录", "取消");
    }

    /**
     * 登录冲突
     */
    private loginConflict() {
        let thiz = this;
        game.askPanel.showMsg(function (r: boolean) {
            if (r) {
                Weixin.getAccessCode(GameConfig.appid, Weixin.shareUrl(1));
            }
            else {
                Weixin.closeWindow();
            }
        }, "登录失败，请检查是否在其他设备登录。\n取消将退出游戏", "重新登录", "取消");
    }

    /**
     * 连接超时
     */
    private connectTimeOut() {
        let thiz = this;
        game.askPanel.showMsg(function (r: boolean) {
            if (r) {
                thiz.connectToServer();
            }
            else {
                Weixin.closeWindow();
            }
        }, "连接超时，是否重新连接？\n取消将退出游戏。", "重新连接", "取消");
    }

    /**
     * 网络不加
     */
    private networkNotgood() {
        let thiz = this;
        game.askPanel.showMsg(function (r: boolean) {
            if (r) {
                thiz.connectToServer();
            }
            else {
                Weixin.closeWindow();
            }
        }, "您的网络不佳，连接已经断开，是否重新连接？\n取消将退出游戏。", "重新连接", "取消");
    }

    /**
     * 没有网络
     */
    private networkIsNot() {
        let thiz = this;
        game.askPanel.showMsg(function (r: boolean) {
            if (r) {
                thiz.connectToServer();
            }
            else {
                Weixin.closeWindow();
            }
        }, "无法检测到网络，请确认网络连接后，尝试重新连接。\n取消将退出游戏。", "重新连接", "取消");
    }
}